package com.margo.project.redis.lock.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisLockService {
	
	private final Logger logger=LoggerFactory.getLogger(RedisLockService.class);
	
	@Autowired
	private StringRedisTemplate redisTemplate;
	
	@Autowired
	private RedisDistributedLock redisDistributedLock;
	
	public String insertDB(String projectId) throws InterruptedException {
		if(redisDistributedLock.lock(projectId, 2000)) {
			try {
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				String date=sdf.format(new Date());
				String value=redisTemplate.opsForValue().get(projectId+":"+date);
				if(value==null) {
					Thread.sleep(1000);
					redisTemplate.opsForValue().set(projectId+":"+date, "success", 2, TimeUnit.DAYS);
					logger.info("执行数据库操作");
					return projectId;
				}else {
					logger.info("数据库已有数据");
				}
			}finally {
				redisDistributedLock.releaseLock(projectId);
			}
			
		}else{
			logger.info("其他人在新增");
		};
		return "fail";
	}
}
